﻿#include "Intro.h"


bool IntroScene::init()
{
	IntroLayer* pIntroLayer = IntroLayer::create();
	this->addChild(pIntroLayer);
    
    return true;
}

bool IntroLayer::init()
{
	winSize = CCDirector::sharedDirector()->getWinSize();
	this->setTouchEnabled(true);
	bEndConnection = false;
	connectionTime = 0;


	userCode = CCUserDefault::sharedUserDefault()->getStringForKey("userCode");


	if(userCode.compare("") == 0)
	{
		CCMenu* menu = CCMenu::create();
		CCLabelTTF* label = CCLabelTTF::create("OK", "맑은 고딕", 40);
		CCMenuItemLabel* menuItem = CCMenuItemLabel::create(label, this, menu_selector(IntroLayer::doOk));
		menuItem->setPosition(ccp(winSize.width * 0.7f, winSize.height * 0.5f));
		menu->addChild(menuItem, 10);

		menu->setPosition(CCPointZero);
		this->addChild(menu, 10);

		edtBox = CCEditBox::create(CCSizeMake(400, 60), CCScale9Sprite::create("rec.png"));
		edtBox->setPosition(ccp(winSize.width * 0.3f, winSize.height * 0.5f));
		edtBox->setFontColor(ccBLACK);
		//edtBox->setPlaceHolder("data");
		edtBox->setMaxLength(45);
		edtBox->setReturnType(kKeyboardReturnTypeDone);
		edtBox->setInputMode(kEditBoxInputModeSingleLine);
		this->addChild(edtBox);

		
	}
	else
	{
		this->schedule(schedule_selector(IntroLayer::update), 1.0f);

		lblLoading = CCLabelTTF::create("Loading...", "맑은 고딕", 40);
		//lblScore->setColor(ccBLACK); 
		lblLoading->setPosition((ccp(winSize.width * 0.5, winSize.height * 0.3)));
		this->addChild(lblLoading, 10);


		CCString* url = CCString::createWithFormat("http://115.71.238.29:8080/SegmentWeb/access/?userCode=%s", userCode.c_str());

		CCHttpRequest* request = new CCHttpRequest();
		request->setUrl(url->getCString());
		request->setRequestType(CCHttpRequest::kHttpGet);

		std::vector<std::string> headers;
		headers.push_back("Content-Type: application/json; charset=utf-8");
		request->setHeaders(headers);
		request->setResponseCallback(this, callfuncND_selector(IntroLayer::accessUserCallBack));

		request->setTag("access");
		CCHttpClient::getInstance()->send(request);
		request->release();
	}

    
    return true;
}

void IntroLayer::update(float dt)
{
	if(connectionTime >= 60)
	{
		CCDirector::sharedDirector()->end();
	}
	else if(connectionTime > 3 && bEndConnection == true)
	{
		lblLoading->setString(CCString::create("Touch GoGo~!")->getCString());
	}
	connectionTime++;
}

void IntroLayer::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
	if(connectionTime > 3 && bEndConnection == true)
	{
		SceneController::runScene(MENU_SCENE);
	}
}


void IntroLayer::createUserCodeCallBack(CCNode *sender, void *data)
{
	CCHttpResponse *response = (CCHttpResponse*)data;

	if(!response)
	{
		return;
	}

	if(!response->isSucceed())
	{
		CCMessageBox(response->getErrorBuffer(),"Response Error");
		return;
	}
	
	// µ•¿Ã≈Õ ¿˙¿Â
	std::vector<char> *buffer = response->getResponseData();
	char* rcvData = (char*)malloc(buffer->size()+1);
	std::string s2(buffer->begin(), buffer->end());

	strcpy(rcvData, s2.c_str());

	
	std::string clearData((const char*)rcvData);
	size_t pos = clearData.rfind("}");
	clearData = clearData.substr(0, pos+1);
	
	if(clearData == "")
	{
		CCMessageBox("데이터가 없습니다.", "Error");
		return;
	}


	Document document;

	if(document.Parse<0>(clearData.c_str()).HasParseError())
	{
		CCMessageBox(document.GetParseError(), "Parse Error");
	}
	else
	{
		assert(document.IsObject());
		assert(document.HasMember("userCode"));
		assert(document["userCode"].IsString());
		

        CCUserDefault::sharedUserDefault()->setStringForKey("userCode", document["userCode"].GetString());
	
		bEndConnection = true;
	}
	
}


void IntroLayer::accessUserCallBack(CCNode *sender, void *data)
{
	CCHttpResponse *response = (CCHttpResponse*)data;

	if(!response)
	{
		return;
	}

	if(!response->isSucceed())
	{
		CCMessageBox(response->getErrorBuffer(),"Response Error");
		return;
	}
	
	// µ•¿Ã≈Õ ¿˙¿Â
	std::vector<char> *buffer = response->getResponseData();
	char* rcvData = (char*)malloc(buffer->size()+1);
	std::string s2(buffer->begin(), buffer->end());

	strcpy(rcvData, s2.c_str());

	
	std::string clearData((const char*)rcvData);
	size_t pos = clearData.rfind("}");
	clearData = clearData.substr(0, pos+1);
	
	if(clearData == "")
	{
		CCMessageBox("데이터가 없습니다.", "Error");
		return;
	}
	else
	{
	
		bEndConnection = true;
	}
}


void IntroLayer::doOk(CCObject* pSender)
{
	this->schedule(schedule_selector(IntroLayer::update), 1.0f);

	lblLoading = CCLabelTTF::create("Loading...", "맑은 고딕", 40);
	//lblScore->setColor(ccBLACK); 
	lblLoading->setPosition((ccp(winSize.width * 0.5, winSize.height * 0.3)));
	this->addChild(lblLoading, 10);

	CCString* url = CCString::createWithFormat("http://115.71.238.29:8080/SegmentWeb/createUserCode/?nickname=%s", edtBox->getText());
	

	CCHttpRequest* request = new CCHttpRequest();
	request->setUrl(url->getCString());
	request->setRequestType(CCHttpRequest::kHttpGet);

	std::vector<std::string> headers;
	headers.push_back("Content-Type: application/json; charset=utf-8");
	request->setHeaders(headers);
	request->setResponseCallback(this, callfuncND_selector(IntroLayer::createUserCodeCallBack));

	request->setTag("userCode");
	CCHttpClient::getInstance()->send(request);
	request->release();



}